package com.yuhs.zixing.pay.util;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Locale;

/**
 * @className: MAC
 * @description: 获取Mac地址
 * @author: xiaofei
 * @create: 2020年01月20日
 */
public final class MAC {

    /**
     * 计算MAC地址.
     * @return
     */
    public final static String getMAC() {
        final java.net.InetAddress address = InetAddress.getInetAddress();
        String mac;
        try {
            final byte[] hardware = NetworkInterface.getByInetAddress(address).getHardwareAddress();
            mac = parseHardwareAddress(hardware);
        } catch (final SocketException e) {
            throw new NetworkException("获取本机MAC地址失败", e);
        }

        return mac.toUpperCase(Locale.CHINA);
    }

    /**
     * 将MAC地址转换为可识别的字符串.
     * @param hardware
     * @return
     */
    private static String parseHardwareAddress(final byte[] hardware) {
        final StringBuilder mac = new StringBuilder();
        for (int i = 0; i < hardware.length; i++) {
            if (i != 0) {
                mac.append(":");
            }
            final String hex = Integer.toHexString(hardware[i] & 0xf);
            mac.append(hex.length() == 1 ? (0 + hex) : hex);
        }
        return mac.toString();
    }

    public MAC() {
        throw new AssertionError("Uninstantiable class.");
    }
}
